package org.Noolab.exec.auth;

import org.NooLab.utilities.strings.ArrUtilities;
import org.NooLab.utilities.strings.StringsUtil;

public class GuidProcessor {

	ArrUtilities arrutil = new ArrUtilities ();
	StringsUtil strgutil = new StringsUtil();
	
	public GuidProcessor(){
		
	}
	
	public String transform( String guidStr, int mode){
		String inGuid = guidStr;
		String preparedGuid , str,str3s, cstr, fxs1,fxs2;
		int[] cfs ;
		int fx1,fx2,p;
		boolean isOdd ;
		
		str3s = inGuid.substring(0,4 );
		preparedGuid = inGuid.substring(4,inGuid.length() );
		
		// preparedGuid = preparedGuid.replace("-", "");
		str = strgutil.makeCharsUnique(preparedGuid);
		cfs = strgutil.frequenciesOfParticles( preparedGuid , str);
		
		fx1 = arrutil.arrayMinPos(cfs);
		fxs1 = str.substring(fx1, fx1+1);
		
		cfs[fx1]=999;
		fx2 = arrutil.arrayMinPos(cfs);
		fxs2 = str.substring(fx2, fx2+1);
		cfs[fx2]=999;
		/*
		 *    this GUID then, either of two procedures will be applied 
		 *    - the most frequent char changes positions with second most frequent char
		 *    - the last position of the most frequent char will exchange position with its left neighbor
		 *    selection of alternatives is by odd of the char value of the most frequent char 
		 */

		char cc = preparedGuid.charAt(fx1);
		int code = (int)cc;
		
		 
		// is ALWAYs odd!!! ( (arrutil.arraySum(cfs))%2==1) ;
		if (cfs[2]<999){
			p=2;
		}else{
			p=3;
		}
		isOdd = ((cfs[p])%2==1) ;
		isOdd = (code%2==1) && isOdd;
		
		// str = arrutil.arr2text(cfs);
		// System.out.println("is odd: "+isOdd+"  "+str);
		
		if (isOdd){

		} else{
			// simply next candidate
			p = arrutil.arrayMinPos(cfs);
			if ((p>0) && (str.substring(p-1, p).contentEquals("-")==false)){
				fx2=p-1 ;				
			}else{
				fx2=p+1 ;
			}
			fxs2 = str.substring(fx2, fx2+1);
			
		}
		preparedGuid = _transformExchange( preparedGuid, fx1,fx2,fxs1,fxs2 );
		
		preparedGuid = str3s+preparedGuid;
		
		return preparedGuid;
	}
	
	private String _transformExchange( String strIn, 
									   int fx1,int fx2,
									   String fxs1, String fxs2 ){
		String preparedGuid = strIn;
		
		preparedGuid = preparedGuid.replace(fxs1, "$?$");
		preparedGuid = preparedGuid.replace(fxs2, "$!$");
		
		preparedGuid = preparedGuid.replace( "$?$", fxs2);
		preparedGuid = preparedGuid.replace("$!$" , fxs1);
		
		return preparedGuid;
	}
}
